<template>
    <view>
        <view class="text-container" @click="dianji">
            <template v-for="(item, index) in parsedTextShow" :key="index">
                <template v-if="item.type === 'text'">
                    <!-- 遍历每个词语并设置长按事件 -->
                    <text 
                        v-for="(word, wordIndex) in item.words" 
                        :key="wordIndex"
                        @longpress="longpressEvent(word, wordIndex, index, $event)"
                        :class="{ actived: isInArray(word, wordIndex, index) }"
                    >{{ word }}</text>
                </template>
                <text v-else-if="item.type === 'other'" class="other-content">{{ item.words }}</text>
                <view v-else-if="item.type === 'newline'" style="height: 20rpx;" tag="这里是换行标签"></view>
            </template>
        </view>
    </view>
    <!-- 长按后显示的浮动菜单 -->
    <view class="tankbox" :class="{show: tankStatus}" :style="'top:'+(tankStatus ? axes.y : -99999)+'px; left: '+ (tankStatus ? axes.x : -99999) + 'px'" @tap.stop>
        <view class="word text-34">{{currentVal.word}}</view>
        <view class="btn" @click="joinEvent">+ 加入生词</view>
    </view>
</template>




<script setup>
	
	import readApi from '@/common/apis/read';
	import { watch, ref, reactive, getCurrentInstance } from 'vue';
	import { postWordJoin_api, getArticleWordsList_api } from '@/common/apis/course';

const { proxy } = getCurrentInstance()
const props = defineProps({
	text: String,
	articleId: String
})

const emit = defineEmits(['callback'])

const symbols = ["(", ")", ",", "?", ";"];

const parsedTextShow = ref([])

const arrayObjects = ref([]);
const templist = ref([])

const isInArray = (data, index, parentIndex) => {
	const inArrayObjects = arrayObjects.value.some(obj => obj.word === data) && isShow.value;
	const inTempList = templist.value.some(obj => obj.word === data);
    return inArrayObjects || inTempList;
}

watch(() => props.text, (newVal) => {
    if(newVal){
        // 拆分成段落
        let paragraphs = newVal.split(/<\/?div>/).filter(p => p.trim() !== '');

        let parsedTexts = [];

        paragraphs.forEach((paragraph, index) => {
            let parts = paragraph.split(/(<other>[^<]*<\/other>)/);

            parts.forEach(part => {
                if (part.startsWith('<other>')) {
                    let content = part.match(/<other>(.*?)<\/other>/)?.[1];
                    if (content) {
                        parsedTexts.push({ type: "other", words: content });
                    }
                } else {
                    let words = part.match(/[\w\u00C0-\u017F']+|[*.,!?;()-]/g).filter(w => w.trim() !== '' && w !== '&nbsp;');
                    if (words.length > 0) {
                        parsedTexts.push({ type: "text", words });
                    }
                }
            });

            if (index < paragraphs.length - 1) {
                parsedTexts.push({ type: "newline" });
            }
        });

        parsedTextShow.value = parsedTexts;
        console.log(parsedTextShow.value);
    }
}, {immediate: true});


const axes = reactive({
	x: 0,
	y: 0
})
const currentVal = reactive({
	word: '',
	parentIndex: 0,
	index: 0
})
const tankStatus = ref(false)

// 处理长按事件以显示 tankbox
function longpressEvent(word, index, parentIndex, events){
	if(templist.value.length){
		templist.value = []
	}
	currentVal.word = word
	currentVal.parentIndex = parentIndex
	currentVal.index = index
	templist.value.push({word, indexs: index, parentIndex})
	
	let sys = uni.getSystemInfoSync()
	
	setTimeout(() => {
		const query = uni.createSelectorQuery().in(proxy);
		console.log(query)
		query.select('.tankbox').boundingClientRect(data => {
			if (data) {
				const width = data.width;
				// #ifdef APP
				const {pageX, pageY} = events.touches[0]
				axes.x = (sys.screenWidth - pageX) > width ? pageX : (pageX - width)
				axes.y = pageY
				// #endif
				
				// #ifdef MP-WEIXIN
				const {x, y} = events.detail
				axes.x = (sys.screenWidth - x) > width ? x : (x - width)
				axes.y = y
				// #endif
				tankStatus.value = true
			}
		}).exec();
	}, 20)
}

// 处理加入生词事件
async function joinEvent(){
	const {word, parentIndex, index} = currentVal
	arrayObjects.value.push({word, indexs: index, parentIndex})
	let res = await postWordJoin_api({articleId: props.articleId, word, type: 2 })
	console.log(res)
	templist.value = []
	uni.showToast({
		title: '加入成功',
		icon: 'success'
	})
	tankStatus.value = false
	emit('callback')
}

// 点击文本容器时隐藏 tankbox
function dianji(){
	if(tankStatus.value){
		tankStatus.value = false
		templist.value.pop()
	}
}

// 切换生词的显示状态
const isShow = ref()
function changeStatus() {
	if (!arrayObjects.value.length) {
		uni.$fui.toast('请先添加生词哦~');
		return;
	};
	
	isShow.value = !isShow.value;
	return true;
}

defineExpose({
	changeStatus,
	setNewWord: list => {
		arrayObjects.value = list;
	}
})
</script>


<style lang="scss" scoped>
.other-content{
	padding: 0 30rpx;
	position: relative;
}
.other-content:after{
	content: '';
	display: block;
	position: absolute;
	left: 0;
	right: 0;
	bottom: 0;
	height: 1px;
	background-color: #000;
}
.text-container{
	display: flex;
	flex-wrap: wrap;
	// font-size: 36rpx;
	font-size: var(--font_cons);
	line-height: 55rpx;
}
text {
  margin-right: 5px;
}
view{
	flex-basis: 100%;
}
.actived{
	background-color: $primary2;
	color: #fff;
}
.tankbox{
	position: fixed;
	background-color: #fff; 
	border-radius: 12rpx;
	box-shadow: 0 0 10rpx rgba(0,0,0,0.5);
	padding: 0 30rpx;
	opacity: 0;
	z-index: 1;
	.word{
		font-weight: 600;
		padding: 20rpx 0;
		border-bottom: 1px solid #f0f2f4;
	}
	.btn{
		text-align: center;
		padding: 20rpx 0;
		color: $primary2;
		font-size: 28rpx;
	}
	&.show{
		opacity: 1;
	}
}
</style>
